<?php


/**
 * Comparator for versions
 *
 * @author Robert
 */


namespace Celebrio\Core;

use Nette\Object;


class VersionComparator extends Object {
    
    
    /**
     * The comparison function returns an integer less than, equal to, or greater than zero
     * if the first argument is considered to be respectively less than, equal to, or greater than the second.
     * 
     */
    public static function compareVersionsAsc($ver1, $ver2) {
        $compResult = self::compareVersions($ver1, $ver2);
        return $compResult;
    }
    
    
    /**
     * The comparison function returns an integer less than, equal to, or greater than zero
     * if the first argument is considered to be respectively greater than, equal to, or less than the second.
     * 
     */
    public static function compareVersionsDesc($ver1, $ver2) {
        $compResult = self::compareVersions($ver1, $ver2);
        return ((-1) * $compResult);
    }
      
    
    /**
     * Versions are in format: number.number.number
     * @param type $ver1
     * @param type $ver2 
     */
    private static function compareVersions($ver1, $ver2) {
        $p_ver1 = explode(".", $ver1);
        $p_ver2 = explode(".", $ver2);
        if(count($p_ver1)!==3 || count($p_ver2)!==3) {
            throw new \Exception("One or both of the versions are not in the correct format.");
        }
        
        $compResult = 0;
        for($i = 0; $i < 3; $i++) {
            $compResult = $p_ver1[$i] - $p_ver2[$i];
            if($compResult !== 0) {
                return $compResult;
            }
        }
        return $compResult;
    }
    
    
}


